package com.Work.auth.service.impl;

import com.Work.auth.mapper.SysDeptMapper;
import com.Work.auth.service.SysDeptService;
import com.Work.model.system.SysDept;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public List<SysDept> findDeptTree() {
        List<SysDept> allDeptList = baseMapper.selectList(null);

        List<SysDept> deptTree = allDeptList.stream()
                .filter(dept -> dept.getParentId() == 0)
                .peek(parentDept -> {
                    parentDept.setChildren(getChildrenDept(parentDept.getId(), allDeptList));
                })
                .collect(Collectors.toList());

        return deptTree;
    }

    private List<SysDept> getChildrenDept(Long parentId, List<SysDept> allDeptList) {
        return allDeptList.stream()
                .filter(dept -> dept.getParentId().equals(parentId))
                .peek(childDept -> {
                    childDept.setChildren(getChildrenDept(childDept.getId(), allDeptList));
                })
                .collect(Collectors.toList());
    }
}